package com.cqhz.quwan.util;

import android.accounts.NetworkErrorException;
import android.content.Context;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by ZBB on 2018/3/27.
 * 基础观察者
 */
public abstract class BaseObserver<T> implements Observer<T>
{

    protected Context mContext;

    public BaseObserver(Context mContext)
    {
        this.mContext = mContext;
    }

    public BaseObserver()
    {
    }

    @Override
    public void onSubscribe(@NonNull Disposable disposable)
    {
        /**
         * 数据请求开始
         */
    }

    @Override
    public void onNext(@NonNull T tBaseEntity)
    {
        try
        {
            onSuccess(tBaseEntity);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(@NonNull Throwable e)
    {
        try
        {
            if (e instanceof ConnectException
                || e instanceof TimeoutException
                || e instanceof NetworkErrorException
                || e instanceof UnknownHostException)
            {
                onFailure(e, true);
            }
            else
            {
                onFailure(e, false);
            }
        }
        catch (Exception error)
        {
            error.printStackTrace();
        }
    }

    @Override
    public void onComplete()
    {

    }

    protected abstract void onFailure(Throwable e, boolean isNetWorkError) throws Exception;

    protected abstract void onSuccess(T baseEntity) throws Exception;

    protected void onCodeError(T baseEntity) throws Exception
    {

    }
}
